import os
import logging
from logging.handlers import TimedRotatingFileHandler

def setup_logging(logger_name, log_dir):
    """Initialize and configure logging system.

    Args:
        logger_name (str): Name of the logger.
        log_dir (str): Directory to store log files.

    Returns:
        logging.Logger: Configured logger instance.
    """
    # 创建日志目录（如果不存在）
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # 设置日志级别
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.INFO)

    # 创建按天滚动的日志处理器
    handler = TimedRotatingFileHandler(
        filename=os.path.join(log_dir, f'{logger_name}.log'),
        when='midnight',  # 每天午夜滚动
        interval=1,  # 每天滚动一次
        backupCount=180  # 保留最近180天的日志
    )
    # 设置日志格式
    handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
    logger.addHandler(handler)

    return logger